package cn.aicnn.chatssespringboot.service.Impl;

import cn.aicnn.chatssespringboot.dto.Chat;
import cn.aicnn.chatssespringboot.dto.ChatRequestDTO;
import cn.aicnn.chatssespringboot.dto.Dialog;
import cn.aicnn.chatssespringboot.persistence.chatMapper;
import cn.aicnn.chatssespringboot.persistence.dialogMapper;
import cn.aicnn.chatssespringboot.service.DialogService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class DialogServiceImpl implements DialogService {
    @Autowired
    dialogMapper dialogMapper;
    @Override
    public int insertTextDialog(int chatId, String question, String answer) {
        Dialog dialog = new Dialog();
        dialog.setChatid(chatId);
        dialog.setQuestion(question);
        dialog.setAnswer(answer);
        dialog.setType(false);
        dialogMapper.insert(dialog);

        QueryWrapper<Dialog> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByAsc("id").last("LIMIT 1");
        Dialog dialog1 = dialogMapper.selectOne(queryWrapper);
        return dialog1.getId();
    }

    //获取dialog并转换成messages
    @Override
    public ArrayList<ChatRequestDTO.ReqMessage> selectReqMessage(int chatId) {
        //获取对话列表
        QueryWrapper<Dialog> dialogQueryWrapper = new QueryWrapper<>();
        dialogQueryWrapper.eq("chatid",chatId);
        List<Dialog> dialogs = dialogMapper.selectList(dialogQueryWrapper);
        //转换对话列表并返回
        return changeDialogToReqMessage(dialogs);
    }

    //把对话列表转换成询问chatGPT的格式
    public ArrayList<ChatRequestDTO.ReqMessage> changeDialogToReqMessage(List<Dialog> dialogs){
        //创建messages
        ArrayList<ChatRequestDTO.ReqMessage> messages = new ArrayList<>();
        for (Dialog dialog : dialogs){
            //创建message
            ChatRequestDTO.ReqMessage userMessage = new ChatRequestDTO.ReqMessage();
            //把问题加进去
            userMessage.setRole("user");
            userMessage.setContent(dialog.getQuestion());
            messages.add(userMessage);

            //创建message
            ChatRequestDTO.ReqMessage assistantMessage = new ChatRequestDTO.ReqMessage();
            //把回答加进去
            assistantMessage.setRole("assistant");
            assistantMessage.setContent(dialog.getAnswer());
            messages.add(assistantMessage);
        }
        return messages;
    }
}
